<template>
  <div class="innerpage" @click="hideSelect">
    <Header active="1"></Header>
    <div
      class="page_banner"
      :style="'background-image:url(' + cateInfo.image + ')'"
    >
      <div class="page-inner">
        <h1 class="f60 font-b">{{ cateInfo.name }}</h1>
      </div>
    </div>
    <Tabs :tabsList="navList" @click="navClick" />
    <div class="page-inner page-padding">
      <div class="products flex">
        <div class="col hasbg">
          <div class="filters">
            <div class="fcon">
              <div class="line full">
                <div class="prico"><i class="iconfont icon-sousuo"></i></div>
                <div class="in" @click="stopPropagation">
                  <input
                    type="text"
                    v-model="tempPost.keyword"
                    @keyup="Search"
                    @input="handleInput"
                    @blur=""
                    placeholder="搜索Chemical Name/APID"
                  />
                  <div class="select" v-if="selectShow">
                    <div
                      class="default"
                      v-if="
                        tempPost.keyword.length >= '2' &&
                        ceshiList.length == '0'
                      "
                    >
                      暂无数据
                    </div>
                    <div class="default" v-if="tempPost.keyword.length < '2'">
                      请输入两个及以上的字符
                    </div>
                    <div
                      @click="(tempPost.keyword = i), (selectShow = false)"
                      class="item"
                      v-for="(i, ind) in ceshiList"
                      :key="ind"
                    >
                      {{ i }}
                    </div>
                  </div>
                </div>
              </div>
              <div class="btns">
                <div class="btn on" @click="handleFilter">檢索</div>
              </div>
            </div>
          </div>
          <!-- <div class="ft">
						<div class="t f36">筛选</div>
					</div> -->
          <div class="filters s2">
            <div class="tit flex">
              <div class="t f16 font-m">
                解剖學治療學及化學 (ATC)分類({{ codeList.length }})
              </div>
              <div class="ico"><i class="iconfont icon-down2"></i></div>
            </div>
            <div class="selectgp">
              <div class="item">
                <div class="ops">
                  <el-checkbox-group v-model="atc_code" @change="handleFilter">
                    <template v-for="j in codeList">
                      <el-checkbox
                          :label="j.ATC_code + '：' + j.code_name_en"
                          :value="j.ATC_code" :title="j.ATC_code + '：' + j.code_name_en" />
                    </template>
                  </el-checkbox-group>
                </div>
              </div>
            </div>
          </div>
          <div class="filters s2">
            <div class="tit flex">
              <div class="t f16 font-m">
                持證商({{ manufacturersList.length }})
              </div>
              <div class="ico"><i class="iconfont icon-down2"></i></div>
            </div>
            <div class="selectgp">
              <div class="item">
                <div class="ops">
                  <el-checkbox-group v-model="mid" @change="handleFilter">
                    <template v-for="j in manufacturersList">
                      <el-checkbox
                          :label="j.company_name"
                          :value="j.id" :title="j.company_name"/>
                    </template>
                  </el-checkbox-group>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="cor">
          <!-- <div class="corTit">
						<div class="t f24 font-m">筛选结果({{ total }})</div>
						<div class="filterTags flex">
							<div class="i" v-for="i in myScreening">{{ i.name }}</div>
						</div>
					</div> -->
          <div
            class="filt flex"
            v-if="post.keyword || atc_codeList.length > 0 || midList.length > 0"
          >
            <div class="li flex" v-if="post.keyword">
              <div class="lt">搜索關鍵字</div>
              <div class="lp flex">
                <div class="d">
                  <span>{{ post.keyword }}</span>
                  <span
                    class="c iconfont icon-close"
                    @click="removeKeyword('keyword')"
                  ></span>
                </div>
              </div>
            </div>
            <div class="li flex" v-if="atc_codeList.length > 0">
              <div class="lt">解刨化学治疗(ATC)分类</div>
              <div class="lp flex">
                <div class="d" v-for="(i, index) in atc_codeList" :key="i">
                  <span>{{ i.ATC_code + ":" + i.code_name_en }}</span>
                  <span
                    class="c iconfont icon-close"
                    @click="removeSelect('atc_code', index)"
                  ></span>
                </div>
              </div>
            </div>
            <div class="li flex" v-if="midList.length > 0">
              <div class="lt">持證商</div>
              <div class="lp flex">
                <div class="d" v-for="(i, index) in midList" :key="i">
                  <span>{{ i.company_name }}</span>
                  <span
                    class="c iconfont icon-close"
                    @click="removeSelect('mid', index)"
                  ></span>
                </div>
              </div>
            </div>
          </div>
          <div class="page_res f16 font-m">
            <span>當前顯示</span
            ><span class="n"
              >{{ (page - 1) * 10 }}-{{ Math.min(page * 10, total) }}</span
            ><span>，共</span><span class="n">{{ total }}</span
            ><span>條結果</span>
          </div>
          <div class="apiList">
            <div class="item flex" v-for="(i, index) in dataList" :kef="index">
              <div class="img">
                <img :src="i.molecular_structure" alt="" />
                <div class="hov flex" v-if="!i.premission || i.expired">
                  <div class="hovp" v-if="token">
                    <div class="ico-lock"></div>
                    <div class="p">
                      Please contact the administrator to grant permission
                    </div>
                  </div>
                  <div v-else class="hovp">
                    <div class="ico-lock"></div>
                    <NuxtLink style="color: #fff" to="/login"
                      >Please log in first</NuxtLink
                    >
                  </div>
                </div>
              </div>
              <div class="itxt">
                <div class="it flex">
                  <div class="tl f18">
                    <!-- <span class="t f24 font-m">{{ i.Name }}</span>
                    <span class="cd">{{ i.ATCCode }}</span> -->
                    <span>{{ i.APID }}</span>
                    <span style="padding-left: 5px;" v-if="i.route">({{ i.route }})</span>
                  </div>
                  <div class="tr" v-if="i.premission && !i.expired">
                    <NuxtLink :to="'/APIs/' + i.APID" @click="setLocalData()"
                      ><span>详情</span><span class="iconfont icon-next"></span
                    ></NuxtLink>
                  </div>
                  <div class="tr disabled" v-else>
                    <span>详情</span><span class="iconfont icon-next"></span>
                  </div>
                </div>
                <div class="ip f16">
                  <div class="li">
                    <b>Chemical Name: </b>&nbsp;<span>{{ i.ingredient }}</span>
                  </div>
                  <div class="li">
                    <b>Product Count: </b>&nbsp;<span>{{
                      i.product_count
                    }}</span>
                  </div>
                  <div class="li">
                    <b>Description: </b>&nbsp;
                    <div class="lr toggleML">
                      <div class="p" v-html="i.description"></div>
                      <div class="zk">
                        <template v-if="i.description && i.description.length > 60">
                          <span>显示更多</span><span>收起</span></template
                        >
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- <div v-else class="register">
						<NuxtLink to="/login">Please log in first</NuxtLink>
						
					</div> -->
          <!-- Pagination -->
          <Pagination
            @change="pageChange"
            :currentPage="page"
            :total="total"
            :nobg="true"
            :count="3"
          />
        </div>
      </div>
    </div>
  </div>
</template>
<script>
useHead({
  title: 'APIs'
});
import {
  apiList,
  apiInfo,
  getCloumnList,
  filter_atc_code,
  filter_manufacturers,
  getCategoryList,
  apis_search_tips,
} from "@/api/sections";
import { ElMessageBox } from "element-plus";
export default {
  async setup() {
    const route = useRoute();
    const info = {
      banner: "/uploadfiles/databaseban.jpg",
      subs: [
        {
          id: "101",
          name: "Manufacturers",
          url: "/Manufacturers",
        },
        {
          id: "102",
          name: "Products",
          url: "/Products",
        },
        {
          id: "103",
          name: "Active Pharmaceutical Ingredient (API)",
          url: "/APIs",
        },
      ],
      filterOptions: [
        {
          name: "Anatomical Therapeutic Chemical (ATC)Classification",
          keyname: "atc_classification",
          options: [
            {
              name: "A-ALIMENTARY TRACT AND METABOLIS...",
              value: 201,
            },
            {
              name: "B-BLOOD AND BLOOD FORMING ORGA...",
              value: 202,
            },
            {
              name: "C-CARDIOVASCULAR S",
              value: 203,
            },
            {
              name: "D-DERMATOLOGICALS",
              value: 204,
            },
            {
              name: "G-GENITO URINARY SYS",
              value: 205,
            },
            {
              name: "H-SYSTEMIC HORMONA",
              value: 206,
            },
            {
              name: "J-ANTIINFECTIVES FOR",
              value: 207,
            },
            {
              name: "L-ANTINEOPLASTIC AD",
              value: 208,
            },
            {
              name: "M-MUSCULO-SKELETA",
              value: 209,
            },
            {
              name: "N-NERVOUS SYSTEM",
              value: 210,
            },
            {
              name: "P-ANTIPARASITIC PRO",
              value: 211,
            },
            {
              name: "R-RESPIRATORY SYSTEM",
              value: 212,
            },
            {
              name: "S-SENSORY ORGANS",
              value: 213,
            },
            {
              name: "V-VARIOUS",
              value: 214,
            },
          ],
        },
        {
          name: "Manufacturers",
          keyname: "manufacturers",
          options: [
            {
              value: 101,
              name: "Advance Pharm.Co., Ltd.",
            },
            {
              value: 102,
              name: "APT Pharma Ltd.",
            },
            {
              value: 103,
              name: "Bright Future Pharmaceutical  Laboratories Limited",
            },
            {
              value: 104,
              name: "Europharm Laboratories Co.,  Ltd.",
            },
            {
              value: 105,
              name: "Fortune Pharmacal Company  Limited",
            },
            {
              value: 106,
              name: "Jean-Marie Pharmacal Co., Ltd.",
            },
            {
              value: 107,
              name: "Karen Laboratories O/B Karen Pharmaceutical CO., Ltd.",
            },
            {
              value: 108,
              name: "Luxembourg Medicine Co. Ltd.",
            },
            {
              value: 109,
              name: "Marching Pharmaceutical  Limited ",
            },
          ],
        },
      ],
    };
    let obj = {};
    info.filterOptions.forEach((i) => {
      obj[i.keyname] = [];
      const qr = route.query[i.keyname];
      if (qr) {
        obj[i.keyname].push(Number(qr));
      }
    });

    const state = useState("global_userInfo");
    return {
      info,
      defaultCheck: obj,
      state,
    };
  },
  data() {
    return {
      keyword: "",
      checkResult: this.defaultCheck,
      list: [],
      navList: [],
      limit: 6,
      dataList: [],
      post: {},
      tempPost: {},
      page: 1,
      cateInfo: {},
      atc_code: [],
      mid: [],
      token: "",
      codeList: [],
      manufacturersList: [],
      pageIndex: 1,
      total: 0,
      filterName: "",
      ceshiList: [],
      selectShow: false,
      tooltipShow: "",
      codetipShow: "",
    };
  },
  methods: {
    hideSelect(){
				this.selectShow=false;
				this.nameSelectShow=false;
				this.ingredientsSelectShow=false;
			},
			stopPropagation(e){
				e.stopPropagation();
			},
    // navClick(){
    // 	window.location.reload();
    // },
    setLocalData() {
      const that = this;
      let keys = ["atc_code", "mid", "midList", "atc_codeList"];
      let data = {};
      keys.forEach((key) => {
        data[key] = that[key];
      });
      data.keyword = that.post.keyword;
      data.page = that.page;
      localStorage.setItem("filterData", JSON.stringify(data));
    },
    removeKeyword(key) {
      var that = this;
      that.post[key] = "";
      that.tempPost[key] = "";
      that.handleFilter();
    },
    removeSelect(key, index) {
      this[key].splice(index, 1);
      this.handleFilter();
    },
    Search: function (e) {
      const that = this;
      if (e.keyCode && e.keyCode == 13) {
        that.handleFilter();
      }
    },
    handleFilter: function () {
      const that = this;
      var obj = {
        ...JSON.parse(JSON.stringify(that.post)),
        ...JSON.parse(JSON.stringify(that.tempPost)),
      };
      that.post = obj;
      that.initData();
    },

    pageChange(e) {
      this.page = e;
      this.getData();
      this.$nextTick(function(){
        window.scrollTo(0,0);
      })
    },
    init() {
      getCategoryList({
        cid: 1420,
      }).then((res) => {
        this.cateInfo = res.data;
      });
      getCloumnList({
        id: 1420,
      }).then((res) => {
        this.navList = res.data;
      });

      filter_atc_code({}).then((res) => {
        this.codeList = res.data;
      });
      filter_manufacturers({}).then((res) => {
        this.manufacturersList = res.data;
      });
    },
    initData() {
      const that = this;
      const data = JSON.parse(localStorage.getItem("filterData"));
      this.page = 1;
      if (data) {
        if (data.keyword) {
          that.post.keyword = data.keyword;
          that.tempPost.keyword = data.keyword;
        }
        Object.keys(data).forEach((k) => {
          that[k] = data[k];
        });
      };
      this.dataList = [];
      this.total = 0;
      this.getData();
      localStorage.removeItem('filterData')
    },
    getData() {
      let post = {
        page: this.page,
        limit: 10,
        token: this.token,
        ...this.post,
      };
      if (this.atc_code.length > 0) {
        post.atc_code = String(this.atc_code);
      }
      if (this.mid.length > 0) {
        post.mid = String(this.mid);
      }
      if (this.$route.query.prod) {
        post.ingredients = this.$route.query.prod;
      }

      if (this.$route.query.id) {
        post.id = this.$route.query.id;
      }

      apiList(post).then((res) => {
        this.dataList = res.data.data;
        this.total = res.data.totalcount;

        this.$nextTick(function () {
          $(".toggleML").each(function () {
            var btn = $(this).find(".zk");
            var short = $(this).find(".span");
            var info = $(this).find(".hid");
            var line = $(this).find(".p");
            short.text(info.text().substr(0, 120) + "...");
            btn.off().click(function () {
              if ($(this).hasClass("act")) {
                $(this).removeClass("act");
                line.removeClass("act");
                short.text(info.text().substr(0, 120) + "...");
              } else {
                $(this).addClass("act");
                line.addClass("act");
                short.html(info.html());
              }
            });
          });
        });
      });
    },
    hasPermision: function (id) {
      const that = this;
      return that.state.permission.includes(id) || false;
    },
    handleInput(e) {
      if (this.tempPost.keyword) {
        apis_search_tips({
          keyword: this.tempPost.keyword,
          maxcount: 20,
        }).then((res) => {
          this.ceshiList = res.data;
          this.selectShow = true;
        });
      } else {
        this.selectShow = false;
      }
    },
    inputBlurred() {
      this.selectShow = false;
    },
    mouseenter(name, id, type) {
      if (type == "manufacturers") {
        if (name.length >= 38) {
          this.tooltipShow = id;
        }
      } else {
        if (name.length >= 38) {
          this.codetipShow = id;
        }
      }
    },
  },
  computed: {
    midList: function () {
      var that = this;
      var res = that.manufacturersList.filter((i) => {
        return that.mid.includes(i.id);
      });
      return res;
    },
    atc_codeList: function () {
      var that = this;
      var res = that.codeList.filter((i) => {
        return that.atc_code.includes(i.ATC_code);
      });
      return res;
    },
    myScreening: function () {
      var that = this;
      let res = [];
      let values = JSON.parse(JSON.stringify(that.checkResult));
      let options = JSON.parse(JSON.stringify(that.info.filterOptions));
      Object.keys(values).forEach(function (key) {
        values[key].forEach((val) => {
          let opt = options.filter((i) => {
            return i.keyname == key;
          });
          opt[0].options.forEach((j) => {
            if (j.value == val) {
              res.push(j);
            }
          });
        });
      });
      return res;
    },
  },
  mounted: function () {
    var that = this;

    if (localStorage.getItem("userinfo")) {
      that.token = JSON.parse(localStorage.getItem("userinfo")).token;
    }
    that.initData();
    that.init();
    that.$nextTick(function () {
      $(".filters .tit").click(function () {
        $(this).find(".ico").toggleClass("act");
        $(this).parents(".filters").find(".ops").slideToggle();
      });

      $(".filters .tit").eq(0).find(".ico").addClass("act");
      $(".filters .tit").eq(0).parents(".filters").find(".ops").slideDown();
    });
  },
  // watch: {
  //   "post.keyword": function () {
  //     this.setLocalData();
  //   },
  //   atc_code: function () {
  //     this.setLocalData();
  //   },
  //   mid: function () {
  //     this.setLocalData();
  //   },
  //   midList: function () {
  //     this.setLocalData();
  //   },
  //   atc_codeList: function () {
  //     this.setLocalData();
  //   },
  // },
};
</script>
<style>
.register {
  text-align: center;
  color: #4bb1b9;
  font-size: 20px;
  padding-bottom: 20px;
}

.u-line-2 {
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  text-overflow: ellipsis;
  white-space: normal;
}
</style>